package com.ns.core.sentinel;

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

import static com.alibaba.csp.sentinel.slots.block.RuleConstant.CONTROL_BEHAVIOR_DEFAULT;

/**
 * Sentinel 限流配置
 *
 * @author lw
 */
@Configuration
public class SentinelConfigure {
    public final static String QPS_LIMIT_GET_USER = "qps-max-1";

    /**
     * 注册Sentinel切面对象
     *
     * @return SentinelResourceAspect
     */
    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        initFlowRules(QPS_LIMIT_GET_USER);
        return new SentinelResourceAspect();
    }

    /**
     * 初始化降级规则
     */
    private static void initFlowRules(String resource) {
        System.out.println("----------------------- 初始化限流规则 ！！！");
        List<FlowRule> rules = new ArrayList<>();
        // 规则  qps > 1 时，触发降级
        FlowRule rule = new FlowRule();
        // 设置资源名称
        rule.setResource(resource);

        // 1秒内请求数：QPS为2
        rule.setCount(1);
        // 需要在限流过滤器中设置对应的解析策略来获取
        // flowRule.setLimitApp(appName);
        // 限流的类型
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setControlBehavior(CONTROL_BEHAVIOR_DEFAULT);
        rules.add(rule);
        // 可创建多个规则
        FlowRuleManager.loadRules(rules);
    }

}
